package com.sunnyweather.android.ui.place

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.sunnyweather.android.MainActivity
import com.sunnyweather.android.databinding.FragmentPlaceBinding
import com.sunnyweather.android.ui.weather.WeatherActivity

class PlaceFragment : Fragment() {

    val viewModel by lazy {
        ViewModelProvider(this)[PlaceViewModel::class.java]
    }

    private lateinit var adapter: PlaceAdapter

    private lateinit var binding: FragmentPlaceBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentPlaceBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        val fragment = this
        activity?.lifecycle?.addObserver(object : LifecycleEventObserver {
            @SuppressLint("NotifyDataSetChanged")
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event.targetState == Lifecycle.State.CREATED) {
                    if (activity is MainActivity && viewModel.isPlaceSaved()) {
                        val place = viewModel.getSavePlace()
                        val intent = Intent(context, WeatherActivity::class.java).apply {
                            putExtra("location_lng", place.location.lng)
                            putExtra("location_lat", place.location.lat)
                            putExtra("place_name", place.name)
                        }
                        startActivity(intent)
                        activity?.finish()
                        return
                    }

                    val layoutManager = LinearLayoutManager(activity)
                    binding.apply {
                        recyclerView.layoutManager = layoutManager
                        adapter = PlaceAdapter(fragment, viewModel.placeList)
                        recyclerView.adapter = adapter
                        searchPlaceEdit.addTextChangedListener { editable ->
                            val content = editable.toString()
                            if (content.isNotEmpty()) {
                                viewModel.searchPlaces(content)
                            } else {
                                recyclerView.visibility = View.GONE
                                bgImageView.visibility= View.VISIBLE
                                viewModel.placeList.clear()
                                adapter.notifyDataSetChanged()
                            }
                        }
                    }
                    viewModel.placeLiveData.observe(fragment) { result ->
                        val places = result.getOrNull()
                        if (places != null) {
                            binding.apply {
                                recyclerView.visibility = View.VISIBLE
                                bgImageView.visibility = View.GONE
                                viewModel.placeList.clear()
                                viewModel.placeList.addAll(places)
                                adapter.notifyDataSetChanged()
                            }
                        } else {
                            Toast.makeText(activity, "未能查询到任何地点", Toast.LENGTH_SHORT).show()
                            result.exceptionOrNull()?.printStackTrace()
                        }
                    }

                    // 移除观察者
                    activity?.lifecycle?.removeObserver(this)
                }
            }
        })
    }
}